package com.dotflat.xj.service.impl;

import com.alibaba.fastjson.JSON;
import com.dotflat.check.domain.Card;
import com.dotflat.check.repository.CardRepository;
import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.dotflat.util.AssertUtil;
import com.dotflat.util.TargetUtil;
import com.dotflat.xj.domain.*;
import com.dotflat.xj.po.*;
import com.dotflat.xj.repository.*;
import com.dotflat.xj.service.TargetClassService;
import com.dotflat.xj.service.TargetService;
import com.dotflat.util.UuidUtil;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.CopyUtils;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.service.remoteCall.SsoCallService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
public class TargetServiceImpl extends AreableObjectBaseServiceImpl<Target, TargetRepository> implements TargetService {

    @Autowired
    @Override
    public void setBaseRepository(TargetRepository repository) {
        super.setBaseRepository(repository);
    }

    @Autowired
    protected MemVerificationCache cache;
    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private CardRepository cardRepository;

    @Autowired
    private TargetProjectValueRepository targetProjectValueRepository;

    @Autowired
    private TargetValueRecordRepository targetValueRecordRepository;

    @Autowired
    private TargetRepository targetRepository;

    @Autowired
    private TargetRecordRepository targetRecordRepository;

    @Autowired
    private DataRepository dataRepository;

    @Autowired
    private TargetClassRepository targetClassRepository;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private TargetClassService targetClassService;

    @Override
    public Target getId(String id) {
        return targetRepository.getOne(id);
    }

    @Override
    public Target save(Target target) {
        return targetRepository.save(target);
    }

    @Override
    public Page<Target> getList(String ticket, String typeName, String status, PagerQuery pagerQuery) {
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        if (Objects.isNull(status)) {
            status = "0";
        }
        String groupId = ssoCallService.getAreaGroupId(ticket);
        List<Target> list = targetRepository.getList(staff.getAreaId(), typeName, status, groupId, pagerQuery.getPageNum() * pagerQuery.getPageSize(), pagerQuery.getPageSize());
        Integer count = targetRepository.getListCount(staff.getAreaId(), typeName, status, groupId);

        return new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), count);
    }

    @Override
    public List<Map> projectList(String ticket, String targetId, String sortName) {
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }

        String sql = " SELECT t.id,t.targetId, IFNULL(t2.sortName,'') parentName ,t.sortName,ifnull(t.parentId,'0') ,ifnull(t.sortValue,'0'),ifnull(t.sortValueLow,'0')    FROM xj_target_project_value t LEFT JOIN xj_target_project_value t2 on t.parentId = t2.id    \n" +
                " where   t.targetId = '" + targetId + "' ";
        if (AssertUtil.isNotEmpty(sortName)) {
            sql += String.format(" and t.sortName like concat('%s', '%s', '%s') ", "%", sortName, "%");
        }
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);

        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            String parentId = objects.get(i)[4].toString();
            if (StringUtils.equals(parentId, "0")) {
                Map map = new HashMap();
                map.put("id", objects.get(i)[0].toString());
                map.put("targetId", objects.get(i)[1].toString());
                map.put("parentName", objects.get(i)[2].toString());
                map.put("sortName", objects.get(i)[3].toString());
                map.put("parentId", objects.get(i)[4].toString());
                mapList.add(map);
                for (int j = 0; j < objects.size(); j++) {
                    String id = objects.get(i)[0].toString();
                    String parentId_1 = objects.get(j)[4].toString();
                    if (StringUtils.equals(parentId_1, id)) {
                        Map map1 = new HashMap();
                        map1.put("id", objects.get(j)[0].toString());
                        map1.put("targetId", objects.get(j)[1].toString());
                        map1.put("parentName", objects.get(j)[2].toString());
                        map1.put("sortName", objects.get(j)[3].toString());
                        map1.put("parentId", objects.get(j)[4].toString());
                        map1.put("sortValue", objects.get(j)[5].toString());
                        map1.put("sortValueLow", objects.get(j)[6].toString());
                        mapList.add(map1);
                        ;
                    }
                }
            }
        }
        return mapList;
    }

    @Override
    public TargetProjectValue addProject(StaffDTO staff,AreaDTO areaDTO, Target target , String sortName, String parentId, String sortValue, String sortValueLow) {

        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "用户不存在！");
        }

        TargetProjectValue targetProjectValue = new TargetProjectValue();
        targetProjectValue.setId(UuidUtil.getUuid());
        targetProjectValue.setAreaId(staff.getAreaId());
        targetProjectValue.setCreatedBy(staff.getId());
        targetProjectValue.setDeleted(false);

        targetProjectValue.setTargetId(target.getId());
        targetProjectValue.setSortName(sortName);
        targetProjectValue.setParentId(parentId);

        targetProjectValue.setSortValue(String.valueOf(TargetUtil.getFraction(target.getConclusionType())));

        if (AssertUtil.isNotEmpty(sortValueLow)) {
            targetProjectValue.setSortValueLow(sortValueLow);
        }

        targetProjectValue = targetProjectValueRepository.save(targetProjectValue);
        return targetProjectValue;
    }

    @Override
    public Map details(String ticket, String targetId) {
        Map map = new HashMap();
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Target target = targetRepository.findAllById(targetId);

        List<TargetProjectValue> list = targetProjectValueRepository.findAllByTargetIdAndParentIdAndStatus(target.getId(), "0", "0");
        List<TargetProjectValueListPO> list1 = new ArrayList<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                TargetProjectValueListPO valueList = new TargetProjectValueListPO();
                TargetProjectValue targetProjectValue = list.get(i);
                CopyUtils.copyProperties(targetProjectValue, valueList);
                List<TargetProjectValue> list2 = targetProjectValueRepository.findAllByTargetIdAndParentIdAndStatus(target.getId(), targetProjectValue.getId(), "0");
                if (list2.size() > 0) {
                    valueList.setTargetProjectValueList(list2);
                }
                list1.add(valueList);
            }
        }
        map.put("target", target);
        map.put("targetProjectValue", list1);
        return map;
    }


    @Override
    public Map getParent(String ticket, String targetId) {
        Map map = new HashMap();
        Target target = targetRepository.findAllById(targetId);
        List<TargetProjectValue> list = targetProjectValueRepository.findAllByTargetIdAndParentIdAndStatus(targetId, "0", "0");
        map.put("target", target);
        map.put("parentList", list);
        return map;
    }


    @Override
    public Map getProject(String ticket, String targetId, String projectId) {
        Map map = new HashMap();
        Target target = targetRepository.getOne(targetId);
        if (AssertUtil.isEmpty(target)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        TargetProjectValue targetProjectValue = targetProjectValueRepository.getOne(projectId);
        if (AssertUtil.isEmpty(targetProjectValue)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        List<TargetProjectValue> list = targetProjectValueRepository.findAllByTargetIdAndParentIdAndStatus(targetId, "0", "0");
        map.put("parentList", list);
        map.put("target", target);
        map.put("targetProjectValue", targetProjectValue);
        return map;
    }


    @Override
    @Transactional
    public TargetProjectValue updateProject(String ticket, String projectId, String sortName, String parentId, String sortValue, String sortValueLow) {

        TargetProjectValue targetProjectValue = targetProjectValueRepository.getOne(projectId);
        if (AssertUtil.isEmpty(targetProjectValue)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Target target = targetRepository.getOne(targetProjectValue.getTargetId());
        if (AssertUtil.isEmpty(target)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        targetProjectValue.setSortName(sortName);
        targetProjectValue.setParentId(parentId);
        if (StringUtils.equals(parentId, projectId)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "父级不能为自己！");
        }
        if (AssertUtil.isNotEmpty(sortValue)) {
            targetProjectValue.setSortValue(sortValue);
        }
        if (AssertUtil.isNotEmpty(sortValueLow)) {
            targetProjectValue.setSortValueLow(sortValueLow);
        }
        targetProjectValueRepository.save(targetProjectValue);
        return targetProjectValue;
    }

    @Override
    public List<Map> appList(String ticket) {
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        List<Map> mapList = new ArrayList<>();
        List<Target> list = targetRepository.getAllAreaId(staff.getAreaId());
        List<Data> list1 = dataRepository.findAllByType("xj_sort");
        if (list1.size() > 0) {
            for (int i = 0; i < list1.size(); i++) {
                Map map = new HashMap();
                map.put("name", list1.get(i).getVal());
                if (list.size() > 0) {
                    List<Map> maps = new ArrayList<>();
                    for (int j = 0; j < list.size(); j++) {
                        Map map1 = new HashMap();
                        if (StringUtils.equals(list.get(j).getSort(), list1.get(i).getVal())) {
                            map1.put("targetId", list.get(j).getId());
                            map1.put("name", list.get(j).getTypeName());
                            maps.add(map1);
                        }
                    }
                    map.put("list", maps);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }


    @Override
    public Map getRecord(String ticket, String targetId) {
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Target target = targetRepository.getOne(targetId);
        if (AssertUtil.isEmpty(target)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Map map = new HashMap();
        map.put("name", staff.getRealName());
        map.put("target", target.getTypeName());

        List<Data> dataList = dataRepository.findAllByTypeAndVal("xj_conclusion_type", target.getConclusionType());

        List<Data> dataList1 = dataRepository.findAllByType(dataList.get(0).getLabel());

        List<TargetProjectValue> list1 = targetProjectValueRepository.getTargetIdList(target.getId());

        List<TargetProjectValue> list3 = targetProjectValueRepository.getTargetId(target.getId());

        List<Map> list = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            Map map1 = new HashMap();
            map1.put("id", list1.get(i).getId());
            map1.put("sortName", list1.get(i).getSortName());
            map1.put("parentId", list1.get(i).getParentId());
            map1.put("valueLow", list1.get(i).getSortValueLow());
            map1.put("value", list1.get(i).getSortValue());
            map1.put("url", "");
            map1.put("content", "");


            map1.put("option", dataList1);

            map1.put("optionVal", "");
            TargetValueRecord targetValueRecord = targetValueRecordRepository.selectTargetValueRecord(staff.getAreaId(), list1.get(i).getId(), DateUtil.convertStr(new Date()) + " 00:00:00");
            if (AssertUtil.isNotEmpty(targetValueRecord)) {
                map1.put("url", targetValueRecord.getUrl());
                map1.put("content", targetValueRecord.getRecordSortValue());
                map1.put("optionVal", TargetUtil.getResultName(dataList1, target.getConclusionType(), targetValueRecord.getRecordSortValue()));
            }
            list.add(map1);
        }
        List<Map> list4 = new ArrayList<>();
        for (int i = 0; i < list3.size(); i++) {
            Map map1 = new HashMap();
            map1.put("id", list3.get(i).getId());
            map1.put("sortName", list3.get(i).getSortName());
            map1.put("parentId", list3.get(i).getParentId());
            map1.put("valueLow", list3.get(i).getSortValueLow());
            map1.put("value", list3.get(i).getSortValue());
            map1.put("url", "");
            map1.put("content", "");
            map1.put("list", "");
            List<Map> list5 = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                if (StringUtils.equals(list3.get(i).getId(), list.get(j).get("parentId").toString())) {
                    list5.add(list.get(j));
                }
                map1.put("list", list5);
            }
            list4.add(map1);
        }
        map.put("parentList", list4);
        return map;
    }

    @Override
    public List<Target> appClassList(String ticket, String classId) {
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        TargetClass targetClass = targetClassRepository.getOne(classId);
        if (AssertUtil.isEmpty(targetClass)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        String groupId = ssoCallService.getAreaGroupId(ticket);
        List<Target> list = targetRepository.targetTypeList(staff.getAreaId(), targetClass.getType(), groupId);
        return list;
    }

    @Override
    public Target stop(String ticket, String targetId, String status) {
        Target target = targetRepository.getOne(targetId);
        if (AssertUtil.isEmpty(target)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        if (StringUtils.equals(target.getAreaId(), "0") && StringUtils.equals(target.getGroupId(), "0")) {
            throw new BusinessException(ErrorCode.IS_TARGET, "公共巡检类别，权限不足！");
        }
        target.setStatus(status);
        targetRepository.save(target);
        return target;
    }

    @Override
    @Transactional
    public void stopProject(String ticket, String projectId) {
        TargetProjectValue targetProjectValue = targetProjectValueRepository.getOne(projectId);
        if (AssertUtil.isEmpty(targetProjectValue)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Target target = targetRepository.getOne(targetProjectValue.getTargetId());
        if (StringUtils.equals(target.getAreaId(), "0") && StringUtils.equals(target.getGroupId(), "0")) {
            throw new BusinessException(ErrorCode.IS_TARGET, "公共巡检类别，权限不足！");
        }
        List<TargetProjectValue> list = targetProjectValueRepository.findAllByTargetIdAndParentId(targetProjectValue.getTargetId(), targetProjectValue.getId());
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            count = count + Integer.parseInt(list.get(i).getSortValue());
            //删除所有关联的子集记录
            targetValueRecordRepository.deleteTargetProjectValueId(list.get(i).getId());
        }
        int projectCount = target.getProjectCount() - count;
        int projectNumber = target.getProjectNumber() - list.size();
        target.setProjectCount(projectCount >= 0 ? projectCount : 0);
        target.setProjectNumber(projectNumber >= 0 ? projectNumber : 0);
        //修改统计项和统计分数
        targetRepository.save(target);
        //删除总项
        targetProjectValueRepository.deleteId(targetProjectValue.getId());
        //删除指定ID的总项
        targetValueRecordRepository.deleteTargetProjectValueId(targetProjectValue.getId());
        //删除分项
        targetProjectValueRepository.deleteParentId(targetProjectValue.getId());
    }


    @Override
    public String importTarget( StaffDTO staffDTO, AreaDTO areaDTO ,String groupId , List<ImportTargetPO> importExcel) {

        if (Objects.isNull(importExcel) || importExcel.size() == 0) {
            throw new BusinessException(ErrorCode.IS_TARGET, "导入数据不能为空");
        }
        Target target = null;
        //记录上级ID
        String parentId = "";
        for (int i = 0; i < importExcel.size(); i++) {
            ImportTargetPO o = importExcel.get(i);
            if (null == o){
                continue;
            }
            TargetClass targetClass = new TargetClass();
            //添加巡检对象
            if (AssertUtil.isNotEmpty(o.getClassName()) && AssertUtil.isNotEmpty(o.getClassTargetType())) {
                targetClass.setName(o.getClassName());
                targetClass.setType(o.getClassTargetType());
                targetClass.setAreaId(staffDTO.getAreaId());
                targetClass.setCreatedBy(staffDTO.getId());
                targetClass = targetClassRepository.save(targetClass);
            }
            //更新卡号
            if (AssertUtil.isNotEmpty(o.getCard())) {
                Card card = cardRepository.findByCardNo(o.getCard());
                if (AssertUtil.isEmpty(card)){
                    card = new Card();
                }
                card.setCreatedBy(staffDTO.getId());
                card.setCardNo(o.getCard());
                card.setCardCode(o.getCard());
                card.setStatus(1);
                card.setPurposeType("巡检");
                card.setType(1);
                cardRepository.save(card);
                targetClass.setCardCode(o.getCard());
                targetClassRepository.save(targetClass);
            }
            if (AssertUtil.isNotEmpty(o.getTypeName()) && AssertUtil.isNotEmpty(o.getTargetType()) &&
                    AssertUtil.isNotEmpty(o.getSort()) && AssertUtil.isNotEmpty(o.getRecordType()) &&
                    AssertUtil.isNotEmpty(o.getCycle()) && AssertUtil.isNotEmpty(o.getConclusionType())) {
                    //巡检对象对象是否存在，不存在就创建
                    target = targetRepository.findByTypeNameAndTargetTypeAndSortAndRecordTypeAndCycleAndConclusionType(o.getTypeName(),
                        o.getTargetType(), o.getSort(), o.getRecordType(), o.getCycle(), o.getConclusionType());
                if (AssertUtil.isEmpty(target)) {
                    target = new Target();
                    target.setTypeName(o.getTypeName());
                    target.setTargetType(o.getTargetType());
                    target.setSort(o.getSort());
                    target.setRecordType(o.getRecordType());
                    target.setCycle(o.getCycle());
                    target.setConclusionType(o.getConclusionType());
                    target.setStatus("0");
                    target.setProjectNumber(0);
                    target.setProjectCount(0);
                    target.setAreaId(staffDTO.getAreaId());
                    target.setBelonging(areaDTO.getName());
                    target.setCreatedBy(staffDTO.getId());
                    if (AssertUtil.isNotEmpty(o.getIsGroup())) {
                        //是否集团共享
                        if (StringUtils.equals(o.getIsGroup(), "是")) {
                            target.setGroupId(String.valueOf(0));
                        } else {
                            target.setGroupId(groupId);
                        }
                    }

                    if (AssertUtil.isNotEmpty(o.getWhole())) {
                        //是否部分提交
                        if (StringUtils.equals(o.getWhole(), "是")) {
                            target.setWhole(String.valueOf(1));
                        } else {
                            target.setGroupId(String.valueOf(0));
                        }
                    }
                    targetRepository.save(target);
                }
            }

            if (AssertUtil.isNotEmpty(o.getSortName())  && AssertUtil.isNotEmpty(target) ){
                if ( AssertUtil.isNotEmpty(o.getParentSortName())  && StringUtils.equals(o.getParentSortName(), "第一级")) {
                    parentId = "0";
                    TargetProjectValue targetProjectValue = addProject(staffDTO,areaDTO, target, o.getSortName(),parentId,null,null);
                    parentId = targetProjectValue.getId();
                }else {
                    addProject(staffDTO,areaDTO, target, o.getSortName(),parentId,null,null);
                    target.setProjectCount(target.getProjectCount() + (TargetUtil.getFraction(target.getConclusionType()) * 1));
                    target.setProjectNumber(target.getProjectNumber() + 1);
                    targetRepository.save(target);
                }

            }

        };
        return "成功";
    }
}